<!-- RoseMap -->
<template>
  <div class="flex">
    <div ref="chart" :style="{ width: '300px', height: '220px' }"></div>
    <div class="data-box">
      <div class="data-box-item flex just-between" v-for="(item, index) in data" :key="index">
        <div class="flex align-center">
          <div class="color-box"></div>
          <div :class="['data-box-name', { selected: seriesIndex === index }]">{{ item.name }}</div>
        </div>
        <div :class="['data-box-count', { selected: seriesIndex === index }]">{{
          item.value + '%'
        }}</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, onMounted, reactive, ref, watch } from 'vue'
  import * as echarts from 'echarts'
  import { getRoseOption } from '@/utils/options'
  import { PieData } from '@/utils/interface'

  interface Props {
    data: Array<PieData>
    interval: number
  }
  const props = defineProps<Props>()

  const chart = ref() // 获取图表
  let eCharts = null // 获取eCharts实例
  let seriesIndex = ref(0) // 当前选中索引值
  let timer = ref(0)

  const renderChart = () => {
    echarts.dispose(chart.value)
    const options = getRoseOption(props.data)
    eCharts = echarts.init(chart.value!)
    eCharts.setOption(options)

    seriesIndex.value = 0
    if (timer.value) {
      clearInterval(timer.value)
    }
    timerInterval(eCharts)
  }

  // 定时高亮
  const timerInterval = (instance: echarts.ECharts) => {
    timer.value = window.setInterval(() => {
      // 定时移除高亮选中区域
      instance.dispatchAction({
        type: 'downplay',
        seriesIndex: 0
      })

      // 选中索引值定时加1
      seriesIndex.value = (seriesIndex.value + 1) % props.data.length

      // 定时高亮
      instance.dispatchAction({
        type: 'highlight',
        dataIndex: seriesIndex.value
      })
    }, props.interval)
  }

  watch(
    props,
    () => {
      renderChart()
    },
    {
      deep: true
    }
  )

  onMounted(() => {
    nextTick(() => {
      renderChart()
    })
  })
</script>
<style lang="scss" scoped>
  .data-box {
    flex: 1;
  }
  .data-box-item {
    font-size: 12px;
    color: #eaecef;
    margin-right: 80px;
  }

  .data-box-name {
    transition: all 0.2s;
  }
  .selected.data-box-name,
  .selected.data-box-count {
    font-size: 14px;
    transition: all 0.2s;
  }
  .data-box-item + .data-box-item {
    margin-top: 15px;
  }
  .color-box {
    width: 6px;
    height: 6px;
    margin-right: 10px;
    background: #cccccc;
  }

</style>
